package com.goldplusgold.tradedelay.app.market.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.support.lib.widget.horizontallistview.SyncHorizontalScrollView;
import com.goldplusgold.support.lib.widget.scroller.ObservableScrollView;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.base.constant.ErrorCodeConstant;
import com.goldplusgold.tradedelay.app.market.MarketManager;
import com.goldplusgold.tradedelay.app.market.activity.QuotationChartActivity;
import com.goldplusgold.tradedelay.app.market.eventbus.DynaMessageEvent;
import com.goldplusgold.tradedelay.app.market.eventbus.FiveRangeMessageEvent;
import com.goldplusgold.network.lib.http.protobuf.Market;
import com.goldplusgold.tradedelay.app.trade.adapter.AdapterPosition;
import com.goldplusgold.tradedelay.app.trade.eventbus.ContractTypeEvent;
import com.goldplusgold.tradedelay.app.trade.networkservice.TradeService;
import com.goldplusgold.tradedelay.app.trade.pojo.OrderResult;
import com.goldplusgold.tradedelay.app.trade.pojo.Position;
import com.goldplusgold.tradedelay.app.trade.pojo.PositionList;
import com.goldplusgold.tradedelay.app.trade.pojo.PositionType;
import com.goldplusgold.tradedelay.app.base.utils.ActivityUtils;
import com.goldplusgold.support.lib.utils.MathUtils;
import com.goldplusgold.support.lib.utils.NetWorkConstant;
import com.goldplusgold.support.lib.utils.StringConvertNumber;
import com.goldplusgold.tradedelay.app.base.widget.TDSureOrderDialog;
import com.goldplusgold.ui.lib.keyboard.KeyboardTouchListener;
import com.goldplusgold.ui.lib.keyboard.KeyboardUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by admin on 2017/5/27.
 */

public class QuickMakeOrderFragment extends BaseFragment implements Handler.Callback, View.OnTouchListener, KeyboardUtil.KeyBoardHeadListener {
    @BindView(R.id.choose_type)
    TextView chooseType;
    @BindView(R.id.choose_type_layout)
    RelativeLayout chooseTypeLayout;
    @BindView(R.id.minus_price_btn)
    ImageView minusPriceBtn;
    @BindView(R.id.minus_price_layout)
    RelativeLayout minusPriceLayout;
    @BindView(R.id.id_text_view_price)
    TextView idTextViewPrice;
    @BindView(R.id.price_line)
    View priceLine;
    @BindView(R.id.et_price)
    EditText etPrice;
    @BindView(R.id.plus_price_btn)
    ImageView plusPriceBtn;
    @BindView(R.id.plus_price_layout)
    RelativeLayout plusPriceLayout;
    @BindView(R.id.minus_quantity_btn)
    ImageView minusQuantityBtn;
    @BindView(R.id.minus_quantity_layout)
    RelativeLayout minusQuantityLayout;
    @BindView(R.id.txt_volume)
    TextView txtVolume;
    @BindView(R.id.volume_line)
    View volumeLine;
    @BindView(R.id.plus_quantity_btn)
    ImageView plusQuantityBtn;
    @BindView(R.id.plus_quantity_layout)
    RelativeLayout plusQuantityLayout;
    @BindView(R.id.et_amount)
    EditText etAmount;
    @BindView(R.id.id_text_view_lasted_price)
    TextView idTextViewLastedPrice;
    @BindView(R.id.newest_goldprice)
    TextView newestGoldprice;
    @BindView(R.id.gold_rose)
    TextView goldRose;
    @BindView(R.id.lastest_price_layout)
    LinearLayout lastestPriceLayout;
    @BindView(R.id.txt_harden)
    TextView txtHarden;
    @BindView(R.id.harden_price)
    TextView hardenPrice;
    @BindView(R.id.harden_price_layout)
    LinearLayout hardenPriceLayout;
    @BindView(R.id.id_text_view_stop_price)
    TextView idTextViewStopPrice;
    @BindView(R.id.drop_stop_price)
    TextView dropStopPrice;
    @BindView(R.id.stop_price_layout)
    LinearLayout stopPriceLayout;
    @BindView(R.id.buy_price)
    TextView buyPrice;
    @BindView(R.id.buy_layout)
    LinearLayout buyLayout;
    @BindView(R.id.sold_price)
    TextView soldPrice;
    @BindView(R.id.sell_layout)
    LinearLayout sellLayout;
    @BindView(R.id.id_text_view_title_position)
    TextView idTextViewTitlePosition;
    @BindView(R.id.id_head_list_view_position)
    LinearLayout idHeadListViewPosition;
    @BindView(R.id.head_content_horsv)
    SyncHorizontalScrollView headContentHorsv;
    @BindView(R.id.id_bottom_list_view_position)
    ListView idBottomListViewPosition;
    @BindView(R.id.buy_btn_tradetype_txt)
    TextView buyBtnTradetypeTxt;
    @BindView(R.id.sold_btn_trade_type_txt)
    TextView soldBtnTradeTypeTxt;
    @BindView(R.id.close_position_price)
    TextView closePositionPrice;
    @BindView(R.id.id_blank_head)
    View mBlankHead;
    @BindView(R.id.id_scroll_view_layout)
    ObservableScrollView mScrollView;

    private Market.InstType mInstType;
    private String lastestPriceValue;
    private String buyOnePriceValue;
    private String soldOnePriceValue;
    private String mTradeTypeCode;
    private String mTradeType;
    private boolean isgetPrice;
    private int priceType = 0;
    private int mTypeFlag = 0;//0,1指黄金类型
    private int currentQuantity = 0;
    private BigDecimal currentUnitPrice = new BigDecimal(0);
    private final int TYPE_RIVAL_PRICE = 0;//对手价
    private final int TYPE_QUEUING_PRICE = 1;//排队价
    private final int TYPE_NEWEST_PRICE = 2;//最新价

    /*持仓类型*/
    private String currentPositionType = null;
    private final String NO_POSITION = "0";//无持仓
    private final String SHORT_POSITIONS = "1";//持空仓
    private final String MULTIPLE_POSITIONS = "2";//持多仓
    private final String SHORT_AND_MULTIPLE_POSITIONS = "3";//持多/空仓
    private String shortOrLongValue;
    /*下单参数*/
    private String mPositionTypeCode;
    private String mUnitPrice;
    private int totalVolume;
    private Handler handler = new Handler(this);
    /*合约持仓总量*/
    //private int prodcodeTotalAmount = 0;

    AdapterPosition mAdapterPosition;

    public static QuickMakeOrderFragment newInstance(Market.InstType instType) {
        QuickMakeOrderFragment f = new QuickMakeOrderFragment();
        Bundle args = new Bundle();
        args.putSerializable("instType", instType);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            mInstType = (Market.InstType) args.getSerializable("instType");
        }
        if (mInstType == Market.InstType.AG_TD) {
            mTradeTypeCode = "Ag(T+D)";
            mTypeFlag = 2;
            mTradeType = "白银延期Ag(T+D)";
        } else if (mInstType == Market.InstType.AU_TD) {
            mTradeTypeCode = "Au(T+D)";
            mTypeFlag = 0;
            mTradeType = "黄金延期Au(T+D)";
        } else {
            mTradeTypeCode = "mAu(T+D)";
            mTypeFlag = 1;
            mTradeType = "迷你黄金延期mAu(T+D)";
        }
        MarketManager.getInstance().sendRequestMsg(mInstType);
        EventBus.getDefault().register(this);
    }



    @Override
    public int getLayoutId() {
        return R.layout.dialog_market_quick_make_order;
    }

    @Override
    public void initView() {
        super.initView();
        chooseType.setText(mTradeType);
        initEditText();
        new GetTradeTypeAsyncTask().execute(AsyncTask.TYPE_NET);
        //new QueryPositionAmountAsyncTask().execute(AsyncTask.TYPE_NET);
        initPosition();
        // 拦截触摸事件，防止泄露下去
        mBlankHead.setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;
    }

    private void initPosition() {
        List<String> titles = Arrays.asList("多/空",
                "可用/手数",
                "开仓均价",
                "浮动盈亏",
                "持仓均价",
                "盯市盈亏");
        for (String str : titles) {
            View childView = LayoutInflater.from(getContext()).inflate(R.layout.item_horizontal_position, idHeadListViewPosition, false);
            TextView mTextViewHorizontal = (TextView) childView.findViewById(R.id.id_text_view_horizontal);
            mTextViewHorizontal.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
            mTextViewHorizontal.setText(str);
            idHeadListViewPosition.addView(childView);
        }

        mAdapterPosition = new AdapterPosition(getActivity(), true);
        mAdapterPosition.addHead(headContentHorsv);
        headContentHorsv.setOnScrollListenter(mAdapterPosition);
        idBottomListViewPosition.setEnabled(false);
        idBottomListViewPosition.setAdapter(mAdapterPosition);
        new LoadPositionsAsyncTask().execute(AsyncTask.TYPE_NET);
    }

    private void initEditText() {
        Activity activity = getActivity();
        if (activity instanceof QuotationChartActivity) {
            KeyboardUtil keyboardUtil = ((QuotationChartActivity) activity).getKeyBoardUtil();
            keyboardUtil.setmKeyBoardHeadListener(this);
            etPrice.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_NUM_POINT, KeyboardTouchListener.TYPE_TOP, mScrollView));
            if (mInstType == Market.InstType.AG_TD
                    || mInstType == Market.InstType.AU_TD) {
                etAmount.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_NUM, KeyboardTouchListener.TYPE_ONE_THOUSAND, mScrollView));
            } else {
                etAmount.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_NUM, KeyboardTouchListener.TYPE_ONE_HUNDRED, mScrollView));
            }
        }

        etPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String inputString = s.toString();
                if (inputString.contains(".")) {
                    if (inputString.length() - 1 - inputString.indexOf(".") > 2) {
                        inputString = (String) inputString.subSequence(0, inputString.indexOf(".") + 3);
                        etPrice.setText(inputString);
                        etPrice.setSelection(inputString.length());
                    }
                }
                if (inputString.trim().equals(".")) {
                    inputString = "0";
                    etPrice.setText(inputString);
                    etPrice.setSelection(1);
                }
                if (inputString.startsWith("0") && inputString.trim().length() > 1) {
                    if (!inputString.substring(1, 2).equals(".")) {
                        etPrice.setText(inputString.subSequence(1, 2));
                        etPrice.setSelection(1);
                        return;
                    }
                }
                if (inputString.length() > 0) {
                    isgetPrice = true;
                    currentUnitPrice = MathUtils.stringToBigDecemal(inputString.trim());
                    etPrice.setSelection(etPrice.getText().length());
                    setTradeButtonText(inputString, inputString);
                    if (!TextUtils.isEmpty(closePositionPrice.getText())) {
                        if ("锁 仓".equals(closePositionPrice.getText()) || "无持仓".equals(closePositionPrice.getText())) {
                            return;
                        }
                        closePositionPrice.setText(inputString);
                    }
                } else {
                    switch (priceType) {
                        case TYPE_RIVAL_PRICE:
                            setTradeButtonText(soldOnePriceValue, buyOnePriceValue);
                            currentUnitPrice = MathUtils.stringToBigDecemal(soldOnePriceValue);
                            if (!TextUtils.isEmpty(shortOrLongValue)) {
                                if ("多".equals(shortOrLongValue)) {
                                    closePositionPrice.setText(buyOnePriceValue);
                                } else {
                                    closePositionPrice.setText(soldOnePriceValue);
                                }
                            }
                            break;
                        case TYPE_QUEUING_PRICE:
                            setTradeButtonText(buyOnePriceValue, soldOnePriceValue);
                            currentUnitPrice = MathUtils.stringToBigDecemal(buyOnePriceValue);
                            if (!TextUtils.isEmpty(shortOrLongValue)) {
                                if ("多".equals(shortOrLongValue)) {
                                    closePositionPrice.setText(soldOnePriceValue);
                                } else {
                                    closePositionPrice.setText(buyOnePriceValue);
                                }
                            }
                            break;
                        case TYPE_NEWEST_PRICE:
                            setTradeButtonText(lastestPriceValue, lastestPriceValue);
                            currentUnitPrice = MathUtils.stringToBigDecemal(lastestPriceValue);
                            if (!TextUtils.isEmpty(closePositionPrice.getText())) {
                                if ("锁 仓".equals(closePositionPrice.getText()) || "无持仓".equals(closePositionPrice.getText())) {
                                    return;
                                }
                                closePositionPrice.setText(lastestPriceValue);
                            }
                            break;
                    }
                    isgetPrice = false;
                }
            }
        });
        etAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    etAmount.setSelection(etAmount.getText().length());
                    currentQuantity = Integer.parseInt(s.toString());
                    minusQuantityLayout.setEnabled(true);
                    minusQuantityBtn.setImageResource(R.drawable.td_minus_icon);
                } else {
                    currentQuantity = 0;
                    minusQuantityLayout.setEnabled(false);
                    minusQuantityBtn.setImageResource(R.drawable.icon_gray_minus);
                }
            }
        });
        etAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (etAmount != null) {
                    if (hasFocus) {
                        etAmount.setHint("");
                    } else {
                        etAmount.setHint("0");
                    }
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void oncontractTypeEventBus(ContractTypeEvent event) {
        if (!isAvailableActivity()) {
            return;
        }
        refreshView();
        shortOrLongValue = event.getLongOrShort();
        if ("Au(T+D)".equals(event.getContractType())) {
            MarketManager.getInstance().sendRequestMsg(Market.InstType.AU_TD);
            mTradeType = "黄金延期Au(T+D)";
        } else if ("mAu(T+D)".equals(event.getContractType())) {
            MarketManager.getInstance().sendRequestMsg(Market.InstType.MAU_TD);
            mTradeType = "迷你黄金延期mAu(T+D)";
        } else {
            MarketManager.getInstance().sendRequestMsg(Market.InstType.AG_TD);
            mTradeType = "白银延期Ag(T+D)";
        }

        switch (priceType) {
            case TYPE_RIVAL_PRICE:
                if ("多".equals(event.getLongOrShort())) {
                    closePositionPrice.setText(buyOnePriceValue);
                } else {
                    closePositionPrice.setText(soldOnePriceValue);
                }
                break;
            case TYPE_QUEUING_PRICE:
                if ("多".equals(event.getLongOrShort())) {
                    closePositionPrice.setText(soldOnePriceValue);
                } else {
                    closePositionPrice.setText(buyOnePriceValue);
                }
                break;
            case TYPE_NEWEST_PRICE:
                closePositionPrice.setText(lastestPriceValue);
                break;

        }

        mTradeTypeCode = event.getContractType();
        chooseType.setText(mTradeType);
        new GetTradeTypeAsyncTask().execute(AsyncTask.TYPE_NET);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQuoteDynaEventBus(DynaMessageEvent event) {
        if (event.getType() == Market.Category.QUOTEDYNA) {
            if (!isAvailableActivity() || !isVisible()) {
                return;
            }
            fillMarketData(event.getQuoteDyna());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFiveRangeEventBus(FiveRangeMessageEvent event) {
        if (event.getType() == Market.Category.QUOTEFIVERANGE) {
            if (!isAvailableActivity() || !isVisible()) {
                return;
            }
            fillFiveRangeData(event.getQuoteFiveRange());
        }
    }

    /*设置交易按钮的文字*/
    private void setTradeButtonText(String value1, String value2) {
        buyPrice.setText(value1);
        soldPrice.setText(value2);
    }

    /*合约切换刷新布局*/
    private void refreshView() {
        isgetPrice = false;
        etAmount.setText("");
        etPrice.setText("");
        currentQuantity = 0;
        shortOrLongValue = "";
    }

    private void showParentRemindLayout(String remindTxt, int type) {
        FragmentActivity activity = getActivity();
        if (activity != null && activity instanceof QuotationChartActivity) {
            ((QuotationChartActivity) activity).showRemindLayout(remindTxt, type);
        }
    }

    /*填充四档数据*/
    private void fillFiveRangeData(Market.QuoteFiveRange quoteFiveRange) {
        soldOnePriceValue = quoteFiveRange.getSellPrice1();
        buyOnePriceValue = quoteFiveRange.getBuyPrice1();
        if (!isgetPrice) {
            switch (priceType) {
                case TYPE_RIVAL_PRICE:
                    currentUnitPrice = MathUtils.stringToBigDecemal(quoteFiveRange.getSellPrice1());
                    setTradeButtonText(quoteFiveRange.getSellPrice1(), quoteFiveRange.getBuyPrice1());
                    if (!TextUtils.isEmpty(currentPositionType)) {
                        switch (currentPositionType) {
                            case SHORT_POSITIONS:
                                closePositionPrice.setText(soldOnePriceValue);
                                break;
                            case MULTIPLE_POSITIONS:
                                closePositionPrice.setText(buyOnePriceValue);
                                break;
                            case SHORT_AND_MULTIPLE_POSITIONS:
                                if (!TextUtils.isEmpty(shortOrLongValue)) {
                                    if ("多".equals(shortOrLongValue)) {
                                        closePositionPrice.setText(buyOnePriceValue);
                                    } else {
                                        closePositionPrice.setText(soldOnePriceValue);
                                    }
                                }
                        }

                    }

                    break;
                case TYPE_QUEUING_PRICE:
                    currentUnitPrice = MathUtils.stringToBigDecemal(quoteFiveRange.getBuyPrice1());
                    setTradeButtonText(quoteFiveRange.getBuyPrice1(), quoteFiveRange.getSellPrice1());
                    if (!TextUtils.isEmpty(currentPositionType)) {
                        switch (currentPositionType) {
                            case SHORT_POSITIONS:
                                closePositionPrice.setText(buyOnePriceValue);
                                break;
                            case MULTIPLE_POSITIONS:
                                closePositionPrice.setText(soldOnePriceValue);
                                break;
                            case SHORT_AND_MULTIPLE_POSITIONS:
                                if (!TextUtils.isEmpty(shortOrLongValue)) {
                                    if ("多".equals(shortOrLongValue)) {
                                        closePositionPrice.setText(soldOnePriceValue);
                                    } else {
                                        closePositionPrice.setText(buyOnePriceValue);
                                    }
                                }
                        }

                        break;
                    }
            }
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (getActivity() == null || getActivity().isFinishing()) {
            return false;
        }
        int type = msg.what;
        switch (type) {
            case NetWorkConstant.NETWORK_ERROR_CODE:
                Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_LONG).show();
                break;
            case NetWorkConstant.NETWORK_SERVER_ERROR_CODE:
                String errorMessage = (String) msg.obj;
                Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
                break;
            case NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE:
                String message = (String) msg.obj;
                ActivityUtils.forceQuit(getActivity(), message);
                break;
        }
        return true;
    }

    @OnClick({R.id.iv_close_dialog, R.id.minus_price_layout, R.id.plus_price_layout, R.id.minus_quantity_layout, R.id.plus_quantity_btn, R.id.buy_layout, R.id.sell_layout, R.id.close_position_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.iv_close_dialog:
                getActivity().onBackPressed();
                break;
            case R.id.minus_price_layout:
                isgetPrice = true;
                if (currentUnitPrice.toString().length() > 0) {
                    if (mTypeFlag == 0 || mTypeFlag == 1) {
                        currentUnitPrice = currentUnitPrice.subtract(BigDecimal.valueOf(0.01));
                    } else {
                        currentUnitPrice = currentUnitPrice.subtract(BigDecimal.valueOf(1));
                    }
                    etPrice.setText(currentUnitPrice.toString());
                    setTradeButtonText(currentUnitPrice.toString(), currentUnitPrice.toString());
                }
                break;
            case R.id.plus_price_layout:
                isgetPrice = true;
                if (mTypeFlag == 0 || mTypeFlag == 1) {
                    currentUnitPrice = currentUnitPrice.add(BigDecimal.valueOf(0.01));
                } else {
                    currentUnitPrice = currentUnitPrice.add(BigDecimal.valueOf(1));
                }
                etPrice.setText(currentUnitPrice.toString());
                setTradeButtonText(currentUnitPrice.toString(), currentUnitPrice.toString());
                break;
            case R.id.minus_quantity_layout:
                if (currentQuantity >= 1) {
                    currentQuantity = currentQuantity - 1;
                    if (currentQuantity == 0) {
                        etAmount.setText("");
                    } else {
                        etAmount.setText(currentQuantity + "");
                    }
                }
                break;
            case R.id.plus_quantity_btn:
                if (currentQuantity < 99999) {
                    etAmount.setSelection(etAmount.getText().length());
                    currentQuantity = currentQuantity + 1;
                    etAmount.setText(currentQuantity + "");
                }

                break;
            case R.id.buy_layout:
                mPositionTypeCode = "4041";
                showOrderDialog(buyPrice.getText().toString(), "开多");
                break;
            case R.id.sell_layout:
                mPositionTypeCode = "4042";
                showOrderDialog(soldPrice.getText().toString(), "开空");
                break;
            case R.id.close_position_layout:
                if (!TextUtils.isEmpty(closePositionPrice.getText().toString())) {
                    if ("锁 仓".equals(closePositionPrice.getText().toString()) || "无持仓".equals(closePositionPrice.getText().toString())) {
                        return;
                    }
                    if (!TextUtils.isEmpty(shortOrLongValue) && "多".equals(shortOrLongValue)) {
                        mPositionTypeCode = "4043";
                        showOrderDialog(closePositionPrice.getText().toString(), "平多");
                    } else {
                        mPositionTypeCode = "4044";
                        showOrderDialog(closePositionPrice.getText().toString(), "平空");
                    }
                }
                break;
        }
    }

    /*订单详情对话框*/
    private void showOrderDialog(String price, String tradeWay) {
        mUnitPrice = price;
        if (TextUtils.isEmpty(etAmount.getText().toString().trim())) {
            showParentRemindLayout("请输入手数", 2);
            return;
        }
        int volume = Integer.parseInt(etAmount.getText().toString().trim());
        totalVolume = volume;
        if (volume == 0) {
            showParentRemindLayout("手数不能为0", 2);
            return;
        }
        switch (mTradeTypeCode) {
            case "Au(T+D)":
                if (volume > 1000) {
                    showParentRemindLayout("已超过持仓限额，您当前可购的最大手数为" + 1000 + "手", 2);
                    return;
                }
                break;
            case "mAu(T+D)":
                if (volume > 10000) {
                    showParentRemindLayout("已超过持仓限额，您当前可购的最大手数为" + 10000 + "手", 2);
                    return;
                }
                break;
            case "Ag(T+D)":
                if (volume > 20000) {
                    showParentRemindLayout("已超过持仓限额，您当前可购的最大手数为" + 20000 + "手", 2);
                    return;
                }
                break;
        }
        if (StringConvertNumber.parseDouble(price) > StringConvertNumber.parseDouble(hardenPrice.getText().toString()) || StringConvertNumber.parseDouble(price) < StringConvertNumber.parseDouble(dropStopPrice.getText().toString())) {
            showParentRemindLayout("委托价格不应超出涨跌停板范围，请修改后下单", 2);
            return;
        }
        TDSureOrderDialog orderDialog = new TDSureOrderDialog(getActivity(), mTradeType, tradeWay, price, volume + "", R.style.AlertDialogStyle);
        orderDialog.setOnSureListener(new TDSureOrderDialog.OnSureListener() {
            @Override
            public void sure() {
                new OrderTransactionAsyncTask().execute(AsyncTask.TYPE_NET);
            }

        });
        orderDialog.show();
    }

    public class OrderTransactionAsyncTask extends AsyncTask<Void, Void, OrderResult> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected OrderResult doInBackground(Void... params) {
            try {
                OrderResult orderResult = TradeService.getInstance().orderTransaction(mPositionTypeCode, mTradeTypeCode, mUnitPrice, totalVolume + "");
                if (orderResult != null) {
                    return orderResult;
                }
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            return null;
        }

        @Override
        protected void onPostExecute(OrderResult orderResult) {
            super.onPostExecute(orderResult);
            dismisLoadingControl();
            if (orderResult == null) {
                return;
            }
            if (orderResult.getStatus()) {
                showParentRemindLayout("下单成功", 1);
            } else {
                showParentRemindLayout(orderResult.getInfo(), 2);
            }
        }
    }

    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);
    }

    public class GetTradeTypeAsyncTask extends AsyncTask<Void, Void, PositionType> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected PositionType doInBackground(Void... params) {
            try {
                PositionType positionType = TradeService.getInstance().getTradeType(mTradeTypeCode);
                if (positionType != null) {
                    return positionType;
                }
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();

            }
            return null;
        }

        @Override
        protected void onPostExecute(PositionType positionType) {
            super.onPostExecute(positionType);
            dismisLoadingControl();
            if (positionType == null) {
                return;
            }

            setButtonInfoBypositionType(positionType);
        }
    }

   /* //查询持仓总量
    public class QueryPositionAmountAsyncTask extends AsyncTask<Void, Void, List<PositionAmount>> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<PositionAmount> doInBackground(Void... params) {
            try {
                List<PositionAmount> positionAmounts = TradeService.getInstance().queryPositionAmount(mTradeTypeCode);
                if (positionAmounts != null) {
                    return positionAmounts;
                }
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<PositionAmount> positionAmounts) {
            super.onPostExecute(positionAmounts);
            if (positionAmounts == null) {
                return;
            }
            prodcodeTotalAmount = positionAmounts.get(0).getTotalAmt();
        }
    }*/

    private void setButtonInfoBypositionType(PositionType positionType) {
        switch (positionType.getType()) {
            case NO_POSITION:
                buyBtnTradetypeTxt.setText("买 多");
                soldBtnTradeTypeTxt.setText("卖 空");
                closePositionPrice.setText("无持仓");
                break;
            case SHORT_POSITIONS:
                buyBtnTradetypeTxt.setText("锁 仓");
                soldBtnTradeTypeTxt.setText("加 空");
                if (priceType == TYPE_QUEUING_PRICE) {
                    closePositionPrice.setText(soldOnePriceValue);
                } else if (priceType == TYPE_RIVAL_PRICE) {
                    closePositionPrice.setText(buyOnePriceValue);
                } else {
                    closePositionPrice.setText(lastestPriceValue);
                }
                break;
            case MULTIPLE_POSITIONS:
                buyBtnTradetypeTxt.setText("加 多");
                soldBtnTradeTypeTxt.setText("锁 仓");

                if (priceType == TYPE_QUEUING_PRICE) {
                    closePositionPrice.setText(soldOnePriceValue);
                } else if (priceType == TYPE_RIVAL_PRICE) {
                    closePositionPrice.setText(buyOnePriceValue);
                } else {
                    closePositionPrice.setText(lastestPriceValue);
                }
                break;
            case SHORT_AND_MULTIPLE_POSITIONS:
                buyBtnTradetypeTxt.setText("加 多");
                soldBtnTradeTypeTxt.setText("加 空");
                if (TextUtils.isEmpty(shortOrLongValue)) {
                    closePositionPrice.setText("锁 仓");
                }
                break;
        }
    }

    /*填充动态数据*/
    private void fillMarketData(Market.QuoteDyna quoteDyna) {
        if ("+".equals(quoteDyna.getUpDownRate().substring(0, 1))) {
            newestGoldprice.setTextColor(getResources().getColor(R.color.shallow_red));
            goldRose.setTextColor(getResources().getColor(R.color.shallow_red));
        } else if ("-".equals(quoteDyna.getUpDownRate().substring(0, 1))) {
            newestGoldprice.setTextColor(getResources().getColor(R.color.color_price_down));
            goldRose.setTextColor(getResources().getColor(R.color.color_price_down));
        } else {
            newestGoldprice.setTextColor(getResources().getColor(R.color.td_color_gray_two));
            goldRose.setTextColor(getResources().getColor(R.color.td_color_gray_two));
        }
        newestGoldprice.setText(quoteDyna.getLastPrice());
        lastestPriceValue = quoteDyna.getLastPrice();
        goldRose.setText("(" + quoteDyna.getUpDownRate() + ")");
        hardenPrice.setText(quoteDyna.getHighestPrice());
        dropStopPrice.setText(quoteDyna.getLowestPrice());
        if (!isgetPrice) {
            if (priceType == TYPE_NEWEST_PRICE) {
                currentUnitPrice = MathUtils.stringToBigDecemal(quoteDyna.getLastPrice());
                setTradeButtonText(quoteDyna.getLastPrice(), quoteDyna.getLastPrice());
                if (!TextUtils.isEmpty(closePositionPrice.getText())) {
                    if ("锁 仓".equals(closePositionPrice.getText()) || "无持仓".equals(closePositionPrice.getText())) {
                        return;
                    }
                    closePositionPrice.setText(quoteDyna.getLastPrice());
                }
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public class LoadPositionsAsyncTask extends AsyncTask<Void, Void, List<Position>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected List<Position> doInBackground(Void... params) {

            try {
                PositionList positionList = TradeService.getInstance().getPositionList(mTradeTypeCode);
                if (positionList != null) {
                    return positionList.getPositions();
                }
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }

            return null;
        }

        @Override
        protected void onPostExecute(List<Position> positionList) {
            super.onPostExecute(positionList);
            if (!isAvailableActivity()) {
                return;
            }
            dismisLoadingControl();
            if (positionList == null || positionList.isEmpty()) {
                return;
            }
            mAdapterPosition.setArrayList(new ArrayList(positionList));
        }
    }

    /*重置当前价格类型下的数据*/
    private void setCurentSelectPriceTypeValue(String priceTypeTxt, int currentPriceType, String currentPrice) {
        etPrice.setText("");
        etPrice.setHint(priceTypeTxt);
        isgetPrice = false;
        priceType = currentPriceType;
        currentUnitPrice = MathUtils.stringToBigDecemal(currentPrice);
    }

    @Override
    public void rivalPrice() {
        setCurentSelectPriceTypeValue("对手价", 0, soldOnePriceValue);
        setTradeButtonText(soldOnePriceValue, buyOnePriceValue);
        if (!TextUtils.isEmpty(shortOrLongValue)) {
            if ("多".equals(shortOrLongValue)) {
                closePositionPrice.setText(buyOnePriceValue);
            } else {
                closePositionPrice.setText(soldOnePriceValue);
            }
        }
    }

    @Override
    public void queuePrice() {
        setCurentSelectPriceTypeValue("排队价", 1, buyOnePriceValue);
        setTradeButtonText(buyOnePriceValue, soldOnePriceValue);
        if (!TextUtils.isEmpty(shortOrLongValue)) {
            if ("多".equals(shortOrLongValue)) {
                closePositionPrice.setText(soldOnePriceValue);
            } else {
                closePositionPrice.setText(buyOnePriceValue);
            }
        }
    }

    @Override
    public void lastedPrice() {
        setCurentSelectPriceTypeValue("最新价", 2, lastestPriceValue);
        setTradeButtonText(lastestPriceValue, lastestPriceValue);
        if (!TextUtils.isEmpty(closePositionPrice.getText())) {
            if ("锁 仓".equals(closePositionPrice.getText()) || "无持仓".equals(closePositionPrice.getText())) {
                return;
            }
            closePositionPrice.setText(lastestPriceValue);
        }
    }
}
